package ren.nearby.http.view.progress;


import android.app.Activity;
import android.app.Dialog;

import android.view.LayoutInflater;
import android.view.View;

import android.widget.TextView;


import com.orhanobut.logger.Logger;

import ren.nearby.http.R;



/**
 * Created by Administrator on 2018/5/24 0024.
 */

public class DialogRequest {

    public static final String TAG_LOGIN = "正在登录，请稍等...";
    public static final String TAG_SEARCH = "正在搜索，请稍等..";
    public static final String TAG_REQUEST = "正在请求，请稍等..";
    private static DialogRequest instance = null;

    private Activity mActivity;

    public static DialogRequest getInstance(Activity activity) {
        if (instance == null) {
            synchronized (DialogRequest.class) {
                if (instance == null) {
                    instance = new DialogRequest(activity);
                }
            }
        }
        return instance;
    }

    private DialogRequest(Activity activity) {
        this.mActivity = activity;

    }


    public DialogRequest builder() {
        return this;
    }


    public DialogRequest show(Activity activity, String msg) {
        Dialog dialog = getDialog(activity, msg);
        dialog.show();
        return this;
    }

    public void dismiss(Activity activity) {
//        Logger.e("dismiss");
        Dialog dialog = getDialog(activity, "");
        dialog.dismiss();
        //关闭后清除不然会报内存泄漏。
        reset();
    }

    Dialog mDialog;

    private Dialog getDialog(Activity activity, String msg) {
        Dialog dialog;
        if (activity == mActivity) {
//            Logger.e("getDialog - mActivity - not - null");
            if (mDialog != null) {
                dialog = mDialog;
//                Logger.e("mDialog - not -  null");
            } else {
//                Logger.e("mDialog - null");
                dialog = createDialog(activity);
            }
        } else {
//            Logger.e("getDialog - mActivity - null");
            reset();
            dialog = createDialog(activity);
            mActivity = activity;

        }
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        TextView view = dialog.findViewById(R.id.tips_loading_msg);
        view.setText(msg);
        return dialog;

    }

    public void reset() {
        mDialog = null;
        mActivity = null;
    }

    Dialog createDialog(Activity activity) {
        View view = LayoutInflater.from(activity).inflate(ren.nearby.http.R.layout.view_tips_loading, null);
        //定义dialog
        mDialog = new Dialog(activity, ren.nearby.http.R.style.request_dialog);
        mDialog.setContentView(view);
        return mDialog;
    }


}
